﻿using Avalonia.Controls;
using Avalonia.Controls.Utils;
using Avalonia.Media;

namespace ExcelMerge;

public class IndexColumn : DataGridTemplateColumn
{
    public int Index { get; }

    public IndexColumn(int index)
    {
        Index = index;
        Header = NumberToExcelColName(index);
    }

    protected override Control GenerateElement(DataGridCell cell, object dataItem)
    {
        if (dataItem is RowData rowData)
        {
            var control = base.GenerateElement(cell, dataItem);
            control.DataContext = rowData.Cells.Count > Index ? rowData.Cells[Index] : null;
            cell.Background = rowData.Cells.Count > Index ? rowData.Cells[Index].Color : new SolidColorBrush(Colors.White);
            return control;
        }
        return base.GenerateElement(cell,dataItem);
    }

    protected override Control GenerateEditingElement(DataGridCell cell, object dataItem, out ICellEditBinding binding)
    {
        if (dataItem is RowData rowData)
        {
            return base.GenerateEditingElement(cell, rowData.Cells[Index],out binding);
        }
        return base.GenerateEditingElement(cell, dataItem, out binding);
    }
    
    private string NumberToExcelColName(int col)
    {
        string result = string.Empty;
        if (col > 26)
        {
            result += NumberToExcelColName((col - 1) / 26);
        }
        result += (char)('A' + (col - 1) % 26);
        return result;
    }
}